package com.yonyou.cyxdms.sysAuth.service.service.manage.ssoRegister;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.cyx.function.exception.DMSAuthException;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.DateUtil;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.EmployeeUpdateDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.UserRegisterDTO;
import com.yonyou.cyxdms.sysAuth.service.entity.EmpPo;
import com.yonyou.cyxdms.sysAuth.service.entity.EmployeePO;
import com.yonyou.cyxdms.sysAuth.service.entity.OrgPO;
import com.yonyou.cyxdms.sysAuth.service.entity.OrgRolePO;
import com.yonyou.cyxdms.sysAuth.service.entity.UserOrgPO;
import com.yonyou.cyxdms.sysAuth.service.entity.UserPO;
import com.yonyou.cyxdms.sysAuth.service.entity.role.RolePO;
import com.yonyou.cyxdms.sysAuth.service.mapper.EmpMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.EmployeeMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.OrgMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.OrgRoleMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.PermissionCtrlMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.PermissionMenuActionMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.PermissionMenuMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.PermissionMenuRangeMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.RoleMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.UserMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.UserOrgMapper;
import com.yonyou.cyxdms.sysAuth.service.utill.MD5Util;
import com.yonyou.cyxdms.sysAuth.service.vo.employee.AddRolePO;

import io.swagger.annotations.Api;

/**
 * 员工用户信息
 *
 * @author xiahy
 * @since 2019/7/9
 */

@Api(value = "员工用户信息", tags = {"员工用户信息"})
@Service
@Transactional(rollbackFor = Exception.class)
public class UserRegisterServiceImpl extends ServiceImpl<EmployeeMapper, EmployeePO> implements UserRegisterService {

    // 定义日志接口
    private static final Logger logger = LoggerFactory.getLogger(UserRegisterServiceImpl.class);

    @Autowired
    private PermissionCtrlMapper permissionCtrlMapper;
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private OrgMapper orgMapper;

    @Autowired
    private UserOrgMapper userOrgMapper;

    @Autowired
    private OrgRoleMapper orgRoleMapper;


    @Autowired
    private PermissionMenuMapper permissionMenuMapper;

    @Autowired
    private PermissionMenuActionMapper permissionMenuActionMapper;

    @Autowired
    private PermissionMenuRangeMapper permissionMenuRangeMapper;



 

    /**
     * @author ：quankk
     * @date ：2019/7/19 11:03
     * @description：新增员工信息
     */
    @Override
    public Long addEmployee(UserRegisterDTO empDto) {
    	logger.info("获取到UserRegisterDTO：{}",empDto);
    	LoginInfoDto loginInfoDto = new LoginInfoDto();
    	loginInfoDto.setAppId(empDto.getAppId());
    	loginInfoDto.setCompanyId(Long.valueOf(1));
    	loginInfoDto.setDataType(Long.valueOf(10461002));
    	logger.info("获取到loginInfoDto：{}",loginInfoDto);
    	//根据传的唯一标识查询用户是否存在
//        SmsWxVo smsWx = userLoginService.getSmsWx(loginInfoDto.getAppId());
        Long companyId = loginInfoDto.getCompanyId();
        String appId = empDto.getAppId();


        UserPO userPoS = userMapper.selectByAppUserCodeOr(appId, empDto.getAccount());
        if (!ObjectUtils.isEmpty(userPoS)) {
            throw new DMSAuthException(995, "该登录账号已被注册");
        }
        logger.info("获取到UserRegisterDTO2：{}",empDto);
        if(!StringUtils.isNullOrEmpty(empDto.getPhone())){
        	 // 查看手机号是否已绑定在职人员
            LambdaQueryWrapper<EmpPo> phoneQueryWrapper = new QueryWrapper().lambda();
            phoneQueryWrapper.eq(EmpPo::getMobilePhone, empDto.getPhone()).eq(EmpPo::getAppId, appId);
            List<EmpPo> phoneEmpPoList = empMapper.selectList(phoneQueryWrapper);
            if (!CommonUtils.isNullOrEmpty(phoneEmpPoList)) {
            	throw new DMSAuthException(995, "该手机号已存在");
            }
        }
        logger.info("获取到UserRegisterDTO3：{}",empDto);

        Integer employeeStatus = 10081001;
        
        // 保存emp表
        EmpPo empPo = new EmpPo();
        empPo.setAppId(empDto.getAppId());
        empPo.setCompanyId(companyId.intValue());
        empPo.setEmployeeName(empDto.getName());
        empPo.setUserCode(empDto.getAccount());
        if(!StringUtils.isNullOrEmpty(empDto.getPhone())) {
        	empPo.setMobilePhone(empDto.getPhone());
        }
        logger.info("输出一下empPo：{}",empPo);
        logger.info("UserRegisterDTO-getAppid：{}",empDto.getAppId());
        logger.info("输出一下empPo-appid：{}",empPo.getAppId());
        empPo.setValidStatus(ManageDictCodeConstants.STATUS_IS_YES);
        if (employeeStatus == ManageDictCodeConstants.EMPLOYEE_ISJOB) {
            empPo.setUserStatus(ManageDictCodeConstants.STATUS_QY);
        } else {
            empPo.setUserStatus(ManageDictCodeConstants.STATUS_JY);
        }
        empPo.setIsOnjob(employeeStatus);
//        Integer gender = employeeAddVO.getGender();
//        if (gender == null) {
//            gender = ManageDictCodeConstants.GENDER_NOT_DEFINE;
//        }
//        empPo.setGender(gender);
        Long dataType = loginInfoDto.getDataType();
        Integer dataSource = null;
        if (dataType == ManageDictCodeConstants.DATA_TYPE_BY_OWNER) {
            dataSource = ManageDictCodeConstants.DATA_SOURCES_BY_OWNER;
        } else if (dataType == ManageDictCodeConstants.DATA_TYPE_BY_GROUP) {
            dataSource = ManageDictCodeConstants.DATA_SOURCES_BY_GROUP;
        } else if (dataType == ManageDictCodeConstants.DATA_TYPE_BY_SUPER) {
            dataSource = ManageDictCodeConstants.DATA_SOURCES_BY_SUPER;
        }
        empPo.setDataSources(dataSource);
        empMapper.insert(empPo);
        
        // 保存user
        UserPO userPo = new UserPO();
//        BeanMapperUtil.copyProperties(employeeAddVO, userPO);
        userPo.setAppId(empDto.getAppId());
        userPo.setEmpId(empPo.getEmpId().intValue());
        userPo.setCompanyId(companyId);
        userPo.setUserCode(empDto.getAccount());
        StringBuilder password = new StringBuilder();
        logger.info("输出一下userPo：{}",userPo);
//        if (smsWx.getSmsType() == ManageDictCodeConstants.STATUS_IS_YES) {
            // CMS-修改密码未固定 a12345678
            password.append("a12345678");
			/*
			 * char[] chars =
			 * "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM".toCharArray(); for
			 * (int i = 0; i < 7; i++) { if (i < 2) { int i1 = RandomUtils.nextInt(0,
			 * chars.length); password.append(chars[i1]); } else { Integer in =
			 * RandomUtils.nextInt(0, 10); password.append(in); } }
			 */
//        } else {
//            if (StringUtils.isNullOrEmpty(employeeAddVO.getPassword())) {
//                throw new DMSAuthException(SysAuthCommonConstants.ERROR_CODE_996, "密码不能为空");
//            }
//            password = new StringBuilder(employeeAddVO.getPassword());
//        }
        String newPassword = MD5Util.getEncryptedPwd(password.toString());
        userPo.setPassword(newPassword);
        userPo.setFailureNum(0);
        userPo.setIsDeleted(0);
        userPo.setLockFlag(10041002);
//        userPO.setLockCause(employeeAddVO.getLockCause());
        if (employeeStatus == ManageDictCodeConstants.EMPLOYEE_ISJOB) {
        	userPo.setUserStatus(ManageDictCodeConstants.STATUS_QY);
        } else {
        	userPo.setUserStatus(ManageDictCodeConstants.STATUS_JY);
        }
        userMapper.insert(userPo);
       

        EmployeePO employeePo = new EmployeePO();
//        BeanMapperUtil.copyProperties(employeeAddVO, employeePO);
        // 保存employee
//        if (type == 3) {
//            LambdaQueryWrapper<EmployeePO> queryWrapper1 = new QueryWrapper<EmployeePO>().lambda();
//            queryWrapper1.select(EmployeePO::getEmployeeId, EmployeePO::getEmployeeNo)
//                    .eq(EmployeePO::getEmpId, empPo.getEmpId()).eq(EmployeePO::getCompanyId, companyId);
//            List<EmployeePO> employeePOS = employeeMapper.selectList(queryWrapper1);
//            if (employeePOS != null && employeePOS.size() > 1) {
//                employeeMapper.deleteByEmployeeIds(
//                        employeePOS.stream().map(EmployeePO::getEmployeeId).collect(Collectors.toList()));
//            } else if (employeePOS != null && employeePOS.size() == 1) {
//                employeePO.setEmployeeId(employeePOS.get(0).getEmployeeId());
//                employeePO.setEmployeeNo(employeePOS.get(0).getEmployeeNo());
//            }
//        }
        employeePo.setAppId(empDto.getAppId());
        employeePo.setOrgId(Long.valueOf(1));
        employeePo.setCompanyId(companyId);
        employeePo.setEmpId(empPo.getEmpId());
        employeePo.setDataType(loginInfoDto.getDataType().intValue());
        employeePo.setValidStatus(ManageDictCodeConstants.STATUS_IS_YES);
        employeePo.setEmployeeStatus(employeeStatus);
        logger.info("输出一下employeePo：{}",employeePo);
//        employeePO.setOwnerCode(orgMapper.getOwerCodebyOrgId(employeePO.getOrgId()));
        Integer maxEmployeeNo = employeeMapper.findMaxEmployeeNo(employeePo.getCompanyId());
        int newNo = maxEmployeeNo + 1;
        String newEmployeeNo = Integer.toString(newNo);
        for (int i = newEmployeeNo.length(); i < 3; i++) {
            newEmployeeNo = "0" + newEmployeeNo;
        }
        newEmployeeNo = empDto.getAppId() + newEmployeeNo;
        employeePo.setEmployeeNo(newEmployeeNo);
        employeeMapper.insert(employeePo);
        AddRolePO addRolePo=new AddRolePO();
        addRolePo.setEmployeeNo(employeePo.getEmployeeNo());
        this.addRole(addRolePo, loginInfoDto,empDto.getAppId());
//        sendpasswordSms(password.toString(), employeeAddVO.getMobilePhone());
        HashMap<String, String> map = new HashMap<>();
        map.put("employeeNo", employeePo.getEmployeeNo());
        map.put("employeeName", empPo.getEmployeeName());
        // 2019-12-17 【更改】将登陆密码显示-START
        map.put("password", password.toString());
        // 2019-12-17 【更改】将登陆密码显示-END
        return null;
    }
    private void setEmployee(EmployeePO employeePo, EmployeeUpdateDTO empDto, Integer empId, LoginInfoDto loginInfoDto) {
    	employeePo.setOrgId((long) empDto.getOrgId());
    	employeePo.setPositionCode(empDto.getPositionCode());
    	employeePo.setIsMajor(ManageDictCodeConstants.STATUS_IS_YES);
    	employeePo.setEmpId(empId.longValue());
    	employeePo.setCompanyId(loginInfoDto.getCompanyId());
			// employeePO.setOwnerCode(orgMapper.getOwerCodebyOrgId(loginInfoDto.getOrgId()));
    	employeePo.setTechnicianGrade(
			!StringUtils.isNullOrEmpty(empDto.getTechnicianGrade()) ? empDto.getTechnicianGrade() : null);
	}
    
    private void setEmp(EmployeeUpdateDTO empDto, EmpPo emp) {
        emp.setEmployeeName(empDto.getEmployeeName());
        emp.setGender(Math.toIntExact(!StringUtils.isNullOrEmpty(empDto.getGender()) ? empDto.getGender()
                : ManageDictCodeConstants.GENDER_NOT_DEFINE));
        emp.setCertificateId(empDto.getCertificateId());
        if(!StringUtils.isNullOrEmpty(empDto.getPhone())) {
        	emp.setMobilePhone(empDto.getPhone());
        }
        emp.seteMail(empDto.geteMail());
        if (empDto.getBirthday() != null) {
            emp.setBirthday(DateUtil.parseDefaultDateTime(empDto.getBirthday()));
        } else {
            emp.setBirthday(new Date());
        }
        emp.setAddress(empDto.getAddress());
        emp.setZipCode(empDto.getZipCode());
        emp.setIsOnjob(empDto.getIsOnjob().intValue());
        emp.setDataSources(ManageDictCodeConstants.DATA_SOURCES_BY_OWNER);
        if (empDto.getIsOnjob() == ManageDictCodeConstants.EMPLOYEE_ISJOB) {
            emp.setUserStatus(ManageDictCodeConstants.STATUS_QY);
        } else {
            emp.setUserStatus(ManageDictCodeConstants.STATUS_JY);
        }

        if (empDto.getFoundDate() != null) {
            emp.setFoundDate(DateUtil.parseDefaultDateTime(empDto.getFoundDate()));
        } else {
            emp.setFoundDate(new Date());
        }

        // 如果在职状态为“离职”并且离职日期为空，则默认离职时间为当前时间
        if ((ManageDictCodeConstants.EMPLOYEE_NOJOB + "").equals(empDto.getIsOnjob() + "")
                && empDto.getDimissionDate() == null) {
            emp.setDimissionDate(new Date());
        } else {
            emp.setDimissionDate(empDto.getDimissionDate());
        }
    }
    
    /**
     * 添加用户角色
     *
     * @author 李贺
     * @date 2019年09月20日
     */
    public Integer addRole(AddRolePO addRolePo,LoginInfoDto loginInfoDto,String appId) {
        Long dataType = loginInfoDto.getDataType();
//        String appId = loginInfoDto.getAppId();
        String employeeNo = addRolePo.getEmployeeNo();
        Long orgId =Long.valueOf(1);
        Integer userId = employeeMapper.findUserIdByNo(employeeNo, appId, loginInfoDto.getCompanyId());


       

        boolean isRole = false;
//        for (RolePO role : employeePOS) {
//            if (BaseDataCommonConstants.ISJL.equals(role.getRoleCode())//IS经理
//                    || BaseDataCommonConstants.CWBJRKRY.equals(role.getRoleCode())
//                    || BaseDataCommonConstants.XSGLBJRGLY.equals(role.getRoleCode())) {
//                isRole = true;
//                UserPO user = userMapper.selectById(userId);
//                user.setRegId(role.getRoleCode());
//                user.setUpdatedAt(LocalDateTime.now());
//                userMapper.updateById(user);
//            }
//        }

            // 插入 userOrg
            UserOrgPO userOrgPo1 = new UserOrgPO();
            userOrgPo1.setUserId(userId.longValue());
            userOrgPo1.setOrgId(orgId);
            userOrgPo1.setRecordVersion(0);
            userOrgPo1.setIsDeleted(0);
            String ownerCode = userOrgMapper.findOwnerCode(orgId.intValue());
            Long ownerId = orgMapper.getOwnerIdByOrgId(orgId);
            if (!StringUtils.isNullOrEmpty(ownerId)) {
                OrgPO orgpo = orgMapper.selectById(ownerId);
                userOrgPo1.setOwnerOrgType(orgpo.getOrgType());
            }
            userOrgPo1.setOwnerCode(ownerCode);
            userOrgMapper.insert(userOrgPo1);

            Long userOrgId = userOrgPo1.getUserOrgId();

            // 删除脏数据
            List<Long> permissionMenuIds = permissionMenuMapper.queryIdByUserOrgId(userOrgId);
            if (permissionMenuIds.size() != 0) {
                // 删除所有 该组织下所有用户权限
                permissionMenuActionMapper.deletePMA(permissionMenuIds);
                permissionMenuRangeMapper.deletePMR(permissionMenuIds);
                permissionMenuMapper.deletePM(permissionMenuIds);
            }
            permissionCtrlMapper.deletePermissionCtrlByUserOrgId(userOrgId);
            
            List<Long> list=new ArrayList<>();
            LambdaQueryWrapper<RolePO> queryWrapper1 = new QueryWrapper<RolePO>().lambda();
            queryWrapper1.eq(RolePO::getRoleCode, "CSHJS");
            List<RolePO> employeePoS = roleMapper.selectList(queryWrapper1);
            for (RolePO role : employeePoS) {
                // 插入orgRole
                OrgRolePO orgRolePo = new OrgRolePO();
                orgRolePo.setUserOrgId(userOrgId);
                orgRolePo.setRoleId(role.getRoleId());
                orgRolePo.setIsDeleted(0);
                orgRoleMapper.insert(orgRolePo);
                list.add(role.getRoleId());
            }
            
            Long createdBy = Long.valueOf(999999);
            permissionMenuMapper.insertUserMenu(list, userOrgId, createdBy, appId);
            permissionMenuMapper.insertOtherMenu(userOrgId, loginInfoDto.getAppId(), createdBy, dataType);
            permissionCtrlMapper.addUserPermissionCtrl(userOrgId, list, userId, appId);
            permissionMenuRangeMapper.insertRangeByOthers(list, ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE,
                    userOrgId, ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, "999999");
            permissionMenuActionMapper.insertActionByOthers(list, ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE,
                    userOrgId, ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, "999999");



        return 1;

    }
  
}
